import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { NavBar, ErrorBlock, Skeleton, Tag } from 'antd-mobile'
import { useNavigate, useParams } from 'react-router-dom'

export type MyTraining = {
  id?: number | string
  name: string
  level?: string
  equipments?: string[]
  parts?: string[]
  warmup?: boolean
  stretch?: boolean
  createdAt?: number
}

export default function SetMyDetail() {
  const navigate = useNavigate()
  const { id } = useParams()
  const [data, setData] = useState<MyTraining | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 15分钟倒计时弹窗状态
  const [showTimer, setShowTimer] = useState(false)
  const [remainSec, setRemainSec] = useState(15 * 60)
  const [isRunning, setIsRunning] = useState(false)
  const [announced, setAnnounced] = useState(false)
  const timerRef = React.useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    const fetch = async () => {
      if (!id) return
      try {
        setError(null)
        setLoading(true)
        const { data } = await axios.get<MyTraining>(`/api/mytrainings/${id}`)
        setData(data)
      } catch (e: any) {
        setError(e?.message || '加载失败')
      } finally {
        setLoading(false)
      }
    }
    fetch()
  }, [id])

  // 开始运动：弹出计时器并启动15分钟倒计时
  const startWorkout = () => {
    setRemainSec(15 * 60)
    setAnnounced(false)
    setShowTimer(true)
    setIsRunning(true)
  }

  // 关闭计时器
  const closeTimer = () => {
    setShowTimer(false)
    setIsRunning(false)
    if (timerRef.current) {
      clearInterval(timerRef.current)
      timerRef.current = null
    }
  }

  // 暂停/继续
  const toggleRun = () => {
    setIsRunning((v) => !v)
  }

  // 计时器副作用
  useEffect(() => {
    if (!showTimer) return
    if (!isRunning) return
    if (remainSec <= 0) return

    timerRef.current = setInterval(() => {
      setRemainSec((s) => s - 1)
    }, 1000)

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current)
        timerRef.current = null
      }
    }
  }, [showTimer, isRunning, remainSec])

  // 结束时提示
  useEffect(() => {
    if (!showTimer) return
    if (remainSec === 0) {
      // 结束
      try {
        if ('speechSynthesis' in window) {
          const utter = new SpeechSynthesisUtterance('本次训练已完成，做得很好！')
          utter.lang = 'zh-CN'
          window.speechSynthesis.speak(utter)
        }
      } catch {}
      setIsRunning(false)
    }
  }, [showTimer, remainSec])

  // 剩余5分钟语音播报
  useEffect(() => {
    if (!showTimer) return
    if (announced) return
    if (remainSec <= 5 * 60) {
      try {
        if ('speechSynthesis' in window) {
          const utter = new SpeechSynthesisUtterance('恭喜您离自己梦想中的样子又近了一步')
          utter.lang = 'zh-CN'
          window.speechSynthesis.speak(utter)
          setAnnounced(true)
        }
      } catch {}
    }
  }, [showTimer, remainSec, announced])

  const formatTime = (sec: number) => {
    const m = Math.floor(sec / 60)
    const s = sec % 60
    return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  }

  // 进度百分比用于环形进度条
  const totalSec = 15 * 60
  const pct = Math.max(0, Math.min(100, (remainSec / totalSec) * 100))

  return (
    <div className="setmy-detail">
      <NavBar
        onBack={() => navigate(-1)}
        style={{ background: 'rgb(227, 83, 26)', color: '#fff' }}
        right={id === '3' ? <span onClick={startWorkout} style={{ fontSize: 14 }}>开始运动</span> : undefined}
      >训练详情</NavBar>

      <div className="content">
        {loading && (
          <div className="loading">
            {Array.from({ length: 3 }).map((_, i) => (
              <Skeleton animated key={i} />
            ))}
          </div>
        )}

        {!loading && error && (
          <ErrorBlock status="default" title="加载失败" description={error} />
        )}

        {!loading && !error && data && (
          <div className="detail-card">
            <div className="row">
              <div className="label">训练名称</div>
              <div className="value name">{data.name}</div>
            </div>
            {data.level && (
              <div className="row">
                <div className="label">级别</div>
                <div className="value"><Tag color="primary" fill="light">{data.level}</Tag></div>
              </div>
            )}
            {data.equipments?.length ? (
              <div className="row">
                <div className="label">器材</div>
                <div className="value chips">
                  {data.equipments.map((e, i) => (
                    <span key={i} className="chip">{e}</span>
                  ))}
                </div>
              </div>
            ) : null}
            {data.parts?.length ? (
              <div className="row">
                <div className="label">训练部位</div>
                <div className="value chips">
                  {data.parts.map((p, i) => (
                    <span key={i} className="chip">{p}</span>
                  ))}
                </div>
              </div>
            ) : null}
            <div className="row">
              <div className="label">包含热身</div>
              <div className="value flag">{data.warmup ? '是' : '否'}</div>
            </div>
            <div className="row">
              <div className="label">包含拉伸</div>
              <div className="value flag">{data.stretch ? '是' : '否'}</div>
            </div>
          </div>
        )}
      </div>

      {showTimer && (
        <div className="timer-overlay">
          <div className="timer-modal">
            <div className="timer-title">运动倒计时</div>
            <div
              className="timer-ring"
              style={{
                background: `conic-gradient(var(--brand) ${pct}%, rgba(0,0,0,0.08) ${pct}% 100%)`,
              }}
            >
              <div className="timer-ring-inner">
                <div className="timer-clock">{formatTime(remainSec)}</div>
              </div>
            </div>
            <div className="timer-actions">
              <button className="btn secondary" onClick={() => setIsRunning(v => !v)}>{isRunning ? '暂停' : '继续'}</button>
              <button className="btn primary" onClick={closeTimer}>{remainSec > 0 ? '结束' : '关闭'}</button>
            </div>
            <div className="timer-tip">剩余5分钟时将自动播报鼓励语</div>
          </div>
        </div>
      )}

      <style>{`
        :root {
          --brand: rgb(227,83,26);
          --brand-600: rgba(227,83,26,0.9);
          --brand-200: rgba(227,83,26,0.12);
        }
        .setmy-detail {
          min-height: 100vh;
          display: flex;
          flex-direction: column;
          background-image:
            linear-gradient(180deg, rgba(255,255,255,0.82) 0%, rgba(255,255,255,0.82) 100%),
            url('/比心.png');
          background-size: cover;
          background-position: center;
          background-attachment: fixed;
        }
        .content { padding: 16px; }
        .loading { display: grid; gap: 12px; }
        .detail-card {
          width: min(360px, 92vw);
          margin: 12px auto 0;
          border-radius: 16px;
          background: rgba(255,255,255,0.6);
          backdrop-filter: blur(6px);
          padding: 14px 16px;
          box-shadow: 0 10px 28px rgba(0,0,0,0.12);
          border: 1px solid rgba(255,255,255,0.6);
        }
        .row { display: flex; justify-content: space-between; align-items: center; padding: 10px 4px; }
        .label { color: #333; font-weight: 600; }
        .value { color: #222; }
        .name { font-weight: 800; font-size: 18px; }
        .chips { display: flex; flex-wrap: wrap; gap: 8px; }
        .chip { background: var(--brand); color: #fff; padding: 4px 10px; border-radius: 999px; font-size: 12px; }
        .flag { font-weight: 700; }

        /* 计时器弹窗样式（主题化 + 玻璃拟态 + 环形进度） */
        .timer-overlay {
          position: fixed;
          inset: 0;
          background: radial-gradient(1200px 600px at 50% -10%, var(--brand-200), transparent 60%), rgba(0,0,0,0.45);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1000;
          padding: 20px;
        }
        .timer-modal {
          width: min(420px, 96vw);
          border-radius: 20px;
          background:
            linear-gradient(180deg, rgba(255,255,255,0.78) 0%, rgba(255,255,255,0.74) 100%);
          border: 1px solid rgba(255,255,255,0.7);
          backdrop-filter: blur(10px);
          padding: 22px 18px 18px;
          box-shadow: 0 18px 48px rgba(0,0,0,0.25);
          text-align: center;
        }
        .timer-title {
          font-size: 16px;
          font-weight: 800;
          color: #333;
          letter-spacing: 0.3px;
          margin-bottom: 12px;
        }
        .timer-ring {
          width: 220px;
          height: 220px;
          border-radius: 50%;
          margin: 0 auto 16px;
          display: grid;
          place-items: center;
          box-shadow: 0 12px 30px rgba(227,83,26,0.22);
          background: conic-gradient(var(--brand) 0%, rgba(0,0,0,0.08) 0% 100%);
        }
        .timer-ring-inner {
          width: 190px;
          height: 190px;
          border-radius: 50%;
          background: #fff;
          display: grid;
          place-items: center;
          box-shadow: inset 0 2px 8px rgba(0,0,0,0.06);
        }
        .timer-clock {
          font-size: 48px;
          font-weight: 900;
          color: var(--brand);
          letter-spacing: 1px;
          text-shadow: 0 6px 18px rgba(227,83,26,0.25);
        }
        .timer-actions { display: flex; gap: 12px; margin: 14px 0 8px; }
        .btn {
          flex: 1;
          height: 46px;
          border-radius: 24px;
          border: none;
          cursor: pointer;
          font-size: 15px;
          font-weight: 800;
          transition: all .2s ease;
        }
        .btn.primary { background: var(--brand); color: #fff; box-shadow: 0 8px 20px rgba(227,83,26,0.35); }
        .btn.primary:hover { filter: brightness(0.98); transform: translateY(-1px); }
        .btn.secondary { background: #fff; color: var(--brand); border: 2px solid var(--brand); }
        .btn.secondary:hover { background: rgba(227,83,26,0.06); transform: translateY(-1px); }
        .btn:active { transform: scale(0.98); }
        .timer-tip { color: #8a8a8a; font-size: 12px; }
      `}</style>
    </div>
  )
}

